package com.jilian.powerstation.modul.natives;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jilian.powerstation.Constant;
import com.jilian.powerstation.MyApplication;
import com.jilian.powerstation.R;
import com.jilian.powerstation.base.BaseActivity;
import com.jilian.powerstation.common.dto.BaseSettingDto;
import com.jilian.powerstation.common.event.MessageEvent;
import com.jilian.powerstation.dialog.nicedialog.BaseNiceDialog;
import com.jilian.powerstation.dialog.nicedialog.NiceDialog;
import com.jilian.powerstation.dialog.nicedialog.ViewConvertListener;
import com.jilian.powerstation.dialog.nicedialog.ViewHolder;
import com.jilian.powerstation.http.SocketConfig;
import com.jilian.powerstation.http.SocketUtils;
import com.jilian.powerstation.modul.activity.LoginActivity;
import com.jilian.powerstation.utils.DataUtils;
import com.jilian.powerstation.utils.EmptyUtils;
import com.jilian.powerstation.utils.NumberUtils;
import com.jilian.powerstation.utils.OnePointLengthFilter;
import com.jilian.powerstation.utils.PinziDialogUtils;
import com.jilian.powerstation.utils.RxTimerUtil;
import com.jilian.powerstation.utils.SPUtil;
import com.jilian.powerstation.utils.ToastUitl;
import com.jilian.powerstation.utils.rxjava.RxBus;
import com.jilian.powerstation.utils.rxjava.RxBusBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Arrays;
import java.util.List;

import io.reactivex.functions.Consumer;

public class BaseSettingActivity extends BaseActivity {
    private LinearLayout llOne;
    private LinearLayout llTwo;
    private TextView tvOne;
    private LinearLayout llThree;
    private RelativeLayout llFour;
    private EditText etOne;
    private RelativeLayout llFive;
    private EditText etTwo;
    private RelativeLayout llSix;
    private RelativeLayout llSeven;
    private EditText etThree;
    private RelativeLayout llEight;
    private EditText etFour;
    private RelativeLayout llNine;
    private EditText etFive;
    private ImageView ivOpenClose;
    private TextView tvReset;


    @Override
    protected void createViewModel() {

    }

    @Override
    public int intiLayout() {
        return R.layout.activity_basesetting;
    }

    @Override
    public void initView() {
        llOne = (LinearLayout) findViewById(R.id.ll_one);
        llTwo = (LinearLayout) findViewById(R.id.ll_two);
        tvOne = (TextView) findViewById(R.id.tv_one);
        llThree = (LinearLayout) findViewById(R.id.ll_three);
        llFour = (RelativeLayout) findViewById(R.id.ll_four);
        etOne = (EditText) findViewById(R.id.et_one);
        llFive = (RelativeLayout) findViewById(R.id.ll_five);
        etTwo = (EditText) findViewById(R.id.et_two);
        llSix = (RelativeLayout) findViewById(R.id.ll_six);
        llSeven = (RelativeLayout) findViewById(R.id.ll_seven);
        etThree = (EditText) findViewById(R.id.et_three);
        llEight = (RelativeLayout) findViewById(R.id.ll_eight);
        etFour = (EditText) findViewById(R.id.et_four);
        llNine = (RelativeLayout) findViewById(R.id.ll_nine);
        etFive = (EditText) findViewById(R.id.et_five);
        ivOpenClose = (ImageView) findViewById(R.id.iv_open_close);
        tvReset = (TextView) findViewById(R.id.tv_reset);

        setNormalTitle("Basic setting", v -> finish());
        setrightTitle("Save", "#3298db", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setting();
            }
        });
        etOne.setFilters(new InputFilter[]{new OnePointLengthFilter()});
        etTwo.setFilters(new InputFilter[]{new OnePointLengthFilter()});
        etThree.setFilters(new InputFilter[]{new OnePointLengthFilter()});
        etFour.setFilters(new InputFilter[]{new OnePointLengthFilter()});
        etFive.setFilters(new InputFilter[]{new OnePointLengthFilter()});


    }
    private boolean isSetting;
    private void setting() {
        if (TextUtils.isEmpty(etOne.getText().toString())
                || TextUtils.isEmpty(etTwo.getText().toString())
                || TextUtils.isEmpty(etThree.getText().toString())
                || TextUtils.isEmpty(etFour.getText().toString())
                || TextUtils.isEmpty(etFive.getText().toString())) {
            ToastUitl.showImageToastTips("Data cannot be empty");

            return;
        }

        int D1 = (int) (Double.parseDouble(etOne.getText().toString()) * 10);
        int baC = (int) (Double.parseDouble(etTwo.getText().toString()) * 10);
        int jiuba = this.jiuba;

        int AA = (int) (Double.parseDouble(etThree.getText().toString()) * 10);
        int A9 = (int) (Double.parseDouble(etFour.getText().toString()) * 10);
        int A8 = (int) (Double.parseDouble(etFive.getText().toString()) * 10);

        Log.e(TAG, "B6: " + B6);
        Log.e(TAG, "D1: " + D1);
        Log.e(TAG, "baC: " + baC);
        Log.e(TAG, "jiuba: " + jiuba);
        Log.e(TAG, "AA: " + AA);
        Log.e(TAG, "A9: " + A9);
        Log.e(TAG, "A8: " + A8);
        isSetting = true;
        RxTimerUtil.cancel();
        RxTimerUtil.timer(16000, new RxTimerUtil.IRxNext() {
            @Override
            public void doNext() {
                if(isSetting){
                    getLoadingDialog().dismiss();
                    ToastUitl.showImageToastTips("Time timeout");
                }
            }
        });
        getLoadingDialog().showDialog();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("基础设置配置命令", "发送的16进制指令: " + DataUtils.hexBytesToString(SocketConfig.baseSetting(B6, D1, baC, jiuba, AA, A9, A8)));
                        SocketUtils.sendSerialPort(SocketConfig.baseSetting(B6, D1, baC, jiuba, AA, A9, A8));
                    }
                }).start();

            }
        }, 10);


    }




    private boolean isOpen;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        // 当按下返回键时所执行的命令
        if (keyCode == KeyEvent.KEYCODE_BACK&&isChange) {
            // 此处写你按返回键之后要执行的事件的逻辑
            showLeaveDialog();
            return false;

        }
        return super.onKeyDown(keyCode, event);

    }

    private boolean isReset;
    private boolean isChange;
    @Override
    public void initListener() {


        etOne.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });
        etTwo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });
        etThree.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });
        etFour.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });
        etFive.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });

        tvReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showConfirmDialog();


            }
        });
        findViewById(R.id.v_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isChange){
                    showLeaveDialog();
                }
                else{
                    finish();
                }
            }
        });


        llOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse("http://10.10.100.254");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
        llTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSelectSettingTypeDialog();
            }
        });
        llThree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(BaseSettingActivity.this, SiteSettingActivity.class));
            }
        });
        ivOpenClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isOpen) {
                    ivOpenClose.setImageResource(R.drawable.image_setting_close);
                    jiuba = 0;
                } else {
                    ivOpenClose.setImageResource(R.drawable.image_setting_open);
                    jiuba = 1;
                }
                isOpen = !isOpen;
                isChange = true;
            }
        });

    }

    private void showConfirmDialog() {
        Dialog dialog = PinziDialogUtils.getDialogNotTouchOutside(this, R.layout.dialog_confirm);
        TextView tvTitle = (TextView) dialog.findViewById(R.id.tv_title);
        TextView tvContent = (TextView) dialog.findViewById(R.id.tv_content);
        TextView tvNo = (TextView) dialog.findViewById(R.id.tv_no);
        TextView tvOk = (TextView) dialog.findViewById(R.id.tv_ok);
        tvTitle.setText("tips");
        tvContent.setText("Whether to confirm the factory reset");

        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isReset = true;
                ToastUitl.showImageToastTips("resetting...");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {

                                Log.e("基础设置配置命令重置", "发送的16进制指令: " + DataUtils.hexBytesToString(SocketConfig.resetSetting()));
                                SocketUtils.sendSerialPort(SocketConfig.resetSetting());
                            }
                        }).start();

                    }
                }, 10);


                sandMessage30();





                dialog.dismiss();

            }
        });
        tvNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();


    }


    private void showSelectSettingTypeDialog() {
        NiceDialog.init()
                .setLayoutId(R.layout.dialog_mppt_select)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        dialog.setOutCancel(false);
                        TextView btnOne = (TextView) holder.getView(R.id.btn_one);
                        TextView btnTwo = (TextView) holder.getView(R.id.btn_two);
                        TextView btnCancel = (TextView) holder.getView(R.id.btn_cancel);
                        btnCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                            }
                        });
                        btnOne.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                tvOne.setText("Parallel");
                                B6 = 1;

                            }
                        });
                        btnTwo.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                dialog.dismiss();

                                tvOne.setText("Single");
                                B6 = 0;
                            }
                        });


                    }
                })
                .setShowBottom(true)
                .show(getSupportFragmentManager());
    }

    private int B6;
    private int jiuba;

    /**
     * 接受到的  基础设置数据
     *
     * @param settingDto
     */
    private void initBaseSetting(BaseSettingDto settingDto) {


        isGetData = true;
        Log.e(TAG, "基础设置界面收到的数据: " + settingDto.toString());
        etFive.setText(NumberUtils.forMatOneNumber(settingDto.getA8() * 0.1));
        etFour.setText(NumberUtils.forMatOneNumber(settingDto.getA9() * 0.1));
        etThree.setText(NumberUtils.forMatOneNumber(settingDto.getAA() * 0.1));
        if (settingDto.getJiuba() == 0) {
            ivOpenClose.setImageResource(R.drawable.image_setting_close);
            jiuba = 0;
        } else {
            ivOpenClose.setImageResource(R.drawable.image_setting_open);
            jiuba = 1;
        }
        etTwo.setText(NumberUtils.forMatOneNumber(settingDto.getBaC() * 0.1));
        etOne.setText(NumberUtils.forMatOneNumber(settingDto.getD1() * 0.1));
        //独立
        if (settingDto.getB6() == 0) {
            B6 = 0;
            tvOne.setText("Single");
        }
        //并联
        else {
            tvOne.setText("Parallel");
            B6 = 1;
        }
        isChange = false;
    }
    private boolean isFront = false;
    @Override
    protected void onResume() {
        super.onResume();
        isFront = true;
        if(dialog!=null){
            dialog.dismiss();
        }

    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        getLoadingDialog().show();
        sandMessage();

    }

    @Override
    protected void onPause() {
        super.onPause();
        isFront = false;
        if (rxBus != null) {
            rxBus.unSubscribe(this);
            rxBus = null;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        MyApplication.removeActivity(this);
        if (rxBus != null) {
            rxBus.unSubscribe(this);
            rxBus = null;
        }

    }

    private void sandMessage30() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("基础设置查询命令", "发送的16进制指令: " + DataUtils.hexBytesToString(SocketConfig.getSetting()));
                        SocketUtils.sendSerialPort(SocketConfig.getSetting());
                    }
                }).start();

            }
        }, 3000);
    }

    /**
     * 查询
     */
    private void sandMessage() {

//        getLoadingDialog().show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("基础设置查询命令", "发送的16进制指令: " + DataUtils.hexBytesToString(SocketConfig.getSetting()));
                        SocketUtils.sendSerialPort(SocketConfig.getSetting());
                    }
                }).start();

            }
        }, 10);
    }





    private String errors[] = new String[]{"Configuration is complete", "After finishing the configuration, power down and restart the device.", "After finishing the configuration, restart in operating mode.", "Disable services for system configuration", "Unable to configure in transparent transmission upgrade", "Parameter out of range", "Parameter ID is not defined", "Parameter conflict, please check"};
    //熊浪添加RxBus工具类，页面销毁时需要取消注册，否则会有内存泄漏
    private RxBus rxBus;
    private boolean isGetData;
    private String tip;


    Dialog dialog;
    /**
     * 退出登录对话框
     */
    private void showTipsDialog(String msg) {
        isChange = false;
         dialog = PinziDialogUtils.getDialogNotTouchOutside(this, R.layout.dialog_confirm);
        TextView tvTitle = (TextView) dialog.findViewById(R.id.tv_title);
        TextView tvContent = (TextView) dialog.findViewById(R.id.tv_content);
        TextView tvNo = (TextView) dialog.findViewById(R.id.tv_no);
        TextView tvOk = (TextView) dialog.findViewById(R.id.tv_ok);
        tvTitle.setText("tips");
        tvContent.setText(msg);
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();

            }
        });
        tvNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
    /**
     * //监听外来是否要去成功的界面
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent event) {
        /* Do something */
        if (EmptyUtils.isNotEmpty(event)
                && EmptyUtils.isNotEmpty(event.getSendMessage())

        ) {

            initSenMessage(event.getSendMessage());
        }
    }

    private void initSenMessage(RxBusBean.SendMessage sendMessage) {
        if(!isFront){
            return;
        }

        //  查询命令
        if (sendMessage != null && sendMessage.readContent[2] == SocketConfig.SEARCH) {
            getLoadingDialog().dismiss();
            Log.e("基础设置查询命令", "我接收到了查询命令的所有数据(已过滤传输规则中其他数据):" + Arrays.toString(sendMessage.info));
            try {
                List<String>infoList = Arrays.asList(sendMessage.info);
                int B6Index = infoList.indexOf("B6");
                int B6 = DataUtils.HexToInt(sendMessage.info[B6Index+2] + sendMessage.info[B6Index+1]);

                int D1Index = infoList.indexOf("D1");
                int D1 = DataUtils.HexToInt(sendMessage.info[D1Index+2] + sendMessage.info[D1Index+1]);

                int baCIndex = infoList.indexOf("8C");
                int baC = DataUtils.HexToInt(sendMessage.info[baCIndex+2] + sendMessage.info[baCIndex+1]);

                int jiu8Index = infoList.indexOf("98");
                int jiuba = DataUtils.HexToInt(sendMessage.info[jiu8Index+2] + sendMessage.info[jiu8Index+1]);

                int AAIndex = infoList.indexOf("AA");
                int AA = DataUtils.HexToInt(sendMessage.info[AAIndex+2] + sendMessage.info[AAIndex+1]);

                int A9Index = infoList.indexOf("A9");
                int A9 = DataUtils.HexToInt(sendMessage.info[A9Index+2] + sendMessage.info[A9Index+1]);

                int A8Index = infoList.indexOf("A8");
                int A8 = DataUtils.HexToInt(sendMessage.info[A8Index+2] + sendMessage.info[A8Index+1]);


                Log.e("基础设置查询命令", "前六位是年月日时分秒:" + DataUtils.HexToInt(sendMessage.info[0]) + "年" + DataUtils.HexToInt(sendMessage.info[1]) + "月" + DataUtils.HexToInt(sendMessage.info[2]) + "日" + DataUtils.HexToInt(sendMessage.info[3]) + "时" + DataUtils.HexToInt(sendMessage.info[4]) + "分" + DataUtils.HexToInt(sendMessage.info[5]) + "秒");
//            int B6 = DataUtils.HexToInt(sendMessage.info[9] + sendMessage.info[8]);
//            Log.e("基础设置查询命令", "MPPT模式: " + B6);
//            int D1 = DataUtils.HexToInt(sendMessage.info[12] + sendMessage.info[11]);
//            Log.e("基础设置查询命令", "馈电功率限值: " + D1);
//            int baC = DataUtils.HexToInt(sendMessage.info[15] + sendMessage.info[14]);
//            Log.e("基础设置查询命令", "市电充电功率限值: " + baC);
//            int jiuba = DataUtils.HexToInt(sendMessage.info[18] + sendMessage.info[17]);
//            Log.e("基础设置查询命令", "EPS功能使能: " + jiuba);
//            int AA = DataUtils.HexToInt(sendMessage.info[21] + sendMessage.info[20]);
//            Log.e("基础设置查询命令", "自发自用截止SOC: " + AA);
//            int A9 = DataUtils.HexToInt(sendMessage.info[24] + sendMessage.info[23]);
//            Log.e("基础设置查询命令", "错峰用电截止SOC: " + A9);
//            int A8 = DataUtils.HexToInt(sendMessage.info[27] + sendMessage.info[26]);
//            Log.e("基础设置查询命令", "电池SOC下限保护: " + A8);
                BaseSettingDto settingDto = new BaseSettingDto(B6, D1, baC, jiuba, AA, A9, A8);
                if(isFront){
                    initBaseSetting(settingDto);
                }
            }
            catch (Exception e){
                ToastUitl.showImageToastFailuer(e.getMessage()+" - ");
            }


        }

        //  设置命令
        else if (sendMessage != null && sendMessage.readContent[2] == SocketConfig.SETTING) {
            isSetting = false;
            getLoadingDialog().dismiss();
            String hexString = DataUtils.ByteArrToHex(sendMessage.readContent);
            Log.e(TAG, "基础设置总的数据:" + hexString);
            Log.e("基础设置设置配置命令", "我接收到了实时信息的所有数据(已过滤传输规则中其他数据):" + Arrays.toString(sendMessage.info));
            Log.e("基础设置设置配置命令", "前六位是年月日时分秒:" + DataUtils.HexToInt(sendMessage.info[0]) + "年" + DataUtils.HexToInt(sendMessage.info[1]) + "月" + DataUtils.HexToInt(sendMessage.info[2]) + "日" + DataUtils.HexToInt(sendMessage.info[3]) + "时" + DataUtils.HexToInt(sendMessage.info[4]) + "分" + DataUtils.HexToInt(sendMessage.info[5]) + "秒");
            int result = DataUtils.HexToInt(sendMessage.info[6]);
            Log.e(TAG, "基础设置设置配置命令accept: " + result);

            if (result == 0 || result == 1 || result == 2 || result == 3 || result == 4 || result == 6) {

                tip = errors[result];
                showTipsDialog(tip);
            } else {
                if (result == 5) {
                    int id = DataUtils.HexToInt(sendMessage.info[7]);
                    double min = DataUtils.HexToInt(sendMessage.info[9] + sendMessage.info[8])*0.1;
                    double max = DataUtils.HexToInt(sendMessage.info[11] + sendMessage.info[10]) * 0.1;
                    //16进制ID
                    String idStr = DataUtils.toHexString(id);
                    //a8  Battery SOC lower limit protection
                    //a9 Force time use cutoff SOC
                    //aa Self use cutoff SOC
                    //8c Feed power limit
                    //d1 Grid power limit
                    if("a8".equals(idStr)){
                        tip = "Battery SOC lower limit protection is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }
                    if("a9".equals(idStr)){
                        tip = "Force time use cutoff SOC is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }
                    if("aa".equals(idStr)){
                        tip = "Self use cutoff SOC is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }
                    if("8c".equals(idStr)){

                        tip = " Grid power limit is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }
                    if("d1".equals(idStr)){
                        tip = "Feed power limit is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }

//                    tip = "Parameter out of range，ID:" + idStr + "  value is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    showTipsDialog(tip);

                } else {
                    tip = "System abnormal, error code is " + sendMessage.info[6];
                    showTipsDialog(tip);
                }
            }
        }

    }

}
